package pl.edu.agh.thieves.gui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import pl.edu.agh.thieves.common.Item;

public class Parser {
	private UserConfiguration config;

	private static Parser instance;

	private Parser() {
		config = UserConfiguration.getInstance();
	}

	public static Parser getInstance() {
		if (instance == null) {
			instance = new Parser();
			return instance;
		} else {
			return instance;
		}

	}

	public void parse() throws IOException {
		File file = config.getFile();
		String lastline = null;
		BufferedReader reader = null;

		try {
			reader = new BufferedReader(new FileReader(file));
			double weight, value;
			double capacity = 0;

			String line;
			String[] lineparts;
			List<Item> items = new ArrayList<Item>();
			boolean capacitydetected = false;
			while ((line = reader.readLine()) != null && !capacitydetected) {
				lineparts = line.split("\t\\s|\\s\t|\\s");
				lastline = lineparts[0];
				if (lineparts.length >= 2) {
					weight = Double.parseDouble(lineparts[0]);
					try {
						value = Double.parseDouble(lineparts[1]);
						if (weight > 0 && value > 0) {
							Item item = new Item(
									Double.parseDouble(lineparts[0]),
									Double.parseDouble(lineparts[1]));
							items.add(item);
						}
					} catch (NumberFormatException e) {
						lastline = lineparts[0];
						capacitydetected = true;
					}
				}
			}
			capacity = Double.parseDouble(lastline);
			config.items.removeAllElements();
			if (capacity > 0) {
				config.setCapacity(capacity);
				for (Item i : items) {
					config.items.addElement(i);
				}
			}
		} finally {
			reader.close();
		}

	}
}
